<template>
  <!-- 使用 grid 网格布局，并指定列数为 2，高度占满全屏 -->
  <div class="grid grid-cols-2 h-screen">
    <!-- 默认占两列，order 用于指定排列顺序，md 用于适配非移动端（PC 端） -->
    <div class="col-span-2 order-2 p-10 md:col-span-1 md:order-1 bg-slate-900">
      <!-- 指定为 flex 布局，并设置为屏幕垂直水平居中，高度为 100% -->
      <div
          class="flex justify-center items-center h-full flex-col animate__animated animate__bounceInLeft animate__fast">
        <h2 class="font-bold text-4xl mb-7 text-white">Weblog 博客注册</h2>
        <p class="text-white">一款由 Spring Boot + Mybaits Plus + Vue 3.2 + Vite 4 开发的前后端分离博客。</p>
        <!-- 指定图片宽度为父级元素的 1/2 -->
        <img src="@/assets/developer.png" class="w-1/2">
      </div>
    </div>
    <div class="flex flex-col col-span-2 order-1 md:col-span-1 md:order-2 bg-white dark:bg-gray-800">

      <!-- 黑夜白天开关 -->
      <label class="switch ml-auto mt-4 mr-4">
        <input type="checkbox" v-model="isLight" @click="toggleDark()">
        <span class="slider"></span>
      </label>

      <!-- flex-col 用于指定子元素垂直排列 -->
      <div
          class="flex justify-center items-center h-full flex-col animate__animated animate__bounceInRight animate__fast">
        <!-- 大标题，设置字体粗细、大小、下边距 -->
        <h1 class="font-bold text-4xl mb-5 dark:text-white">欢迎加入</h1>
        <!-- 设置 flex 布局，内容垂直水平居中，文字颜色，以及子内容水平方向 x 轴间距 -->
        <div class="flex items-center justify-center mb-7 text-gray-400 space-x-2 dark:text-gray-500">
          <!-- 左边横线，高度为 1px, 宽度为 16，背景色设置 -->
          <span class="h-[1px] w-16 bg-gray-200 dark:bg-gray-700"></span>
          <span>账号注册</span>
          <span style="font-size: 12px;margin-left: 10px">已有帐号？<router-link to="/login" style="color: blue">去登陆</router-link></span>
          <!-- 右边横线 -->
          <span class="h-[1px] w-16 bg-gray-200 dark:bg-gray-700"></span>
        </div>
        <!-- 引入 Element Plus 表单组件，调整表单宽度为更合适的比例 -->
        <el-form class="w-5/6 md:w-1/2 lg:w-2/5" ref="formRef" :rules="rules" :model="form">
          <el-form-item prop="username">
            <!-- 输入框组件 -->
            <el-input size="large" v-model="form.username" placeholder="请输入用户名" :prefix-icon="User" clearable/>
          </el-form-item>
          <el-form-item prop="email">
            <!-- 邮箱输入框组件 -->
            <el-input size="large" v-model="form.email" placeholder="请输入邮箱" :prefix-icon="Message" clearable/>
          </el-form-item>
          <el-form-item prop="code">
            <div class="flex w-full gap-2">
              <el-input size="large" v-model="form.code" placeholder="请输入验证码" :prefix-icon="Key" clearable/>
              <el-button size="large" :disabled="countdown > 0" @click="getCode">
                {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
              </el-button>
            </div>
          </el-form-item>
          <el-form-item prop="password">
            <!-- 密码框组件 -->
            <el-input size="large" type="password" v-model="form.password" placeholder="请输入密码"
                      :prefix-icon="Lock" clearable show-password/>
          </el-form-item>
          <el-form-item prop="confirmPassword">
            <!-- 确认密码框组件 -->
            <el-input size="large" type="password" v-model="form.confirmPassword" placeholder="请确认密码"
                      :prefix-icon="Lock" clearable show-password/>
          </el-form-item>
          <el-form-item>
            <!-- 注册按钮，宽度设置为 100% -->
            <el-button class="w-full mt-2" size="large" :loading="loading" type="primary" @click="onSubmit">注册
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, onBeforeUnmount} from 'vue'
import {useDark, useToggle} from '@vueuse/core'
import {User, Lock, Message, Key} from '@element-plus/icons-vue'
import {register, sendEmail} from '@/api/admin/user'
import { useRouter } from 'vue-router'

const router = useRouter();

// 表单数据
const form = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  code: ''
})

// 表单引用
const formRef = ref(null)

// 验证规则
const rules = {
  username: [
    {required: true, message: '用户名不能为空', trigger: 'blur'}
  ],
  email: [
    {required: true, message: '邮箱不能为空', trigger: 'blur'},
    {type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change']}
  ],
  password: [
    {required: true, message: '密码不能为空', trigger: 'blur'},
    {min: 6, message: '密码长度不能少于6位', trigger: 'blur'}
  ],
  confirmPassword: [
    {required: true, message: '请确认密码', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value !== form.value.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  code: [
    {required: true, message: '验证码不能为空', trigger: 'blur'}
  ]
}

// 验证码倒计时
const countdown = ref(0)
let timer = null

const getCode = async () => {
  try {
    // 验证邮箱是否填写
    if (!form.value.email) {
      ElMessage.error('请先填写邮箱')
      return
    }

    // 发送验证码请求
    const res = await sendEmail(form.value.email)

    // 开始倒计时
    countdown.value = 60
    timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)

    if (res.success === true) {
      ElMessage.success('验证码发送成功')
    }
  } catch (error) {
    ElMessage.error(error.message || '发送验证码失败')
  }
}

// 表单提交
const loading = ref(false)
const onSubmit = async () => {
  try {
    // 表单验证
    await formRef.value.validate()

    loading.value = true
    // 调用注册接口
    const res = await register(
        form.value.username,
        form.value.password,
        form.value.confirmPassword,
        form.value.email,
        form.value.code
    )

    if (res.success === true) {

      ElMessage.success('注册成功')
      // 这里可以添加注册成功后的跳转逻辑
      router.push('/login');

    }else {
      ElMessage.error(res.message)
    }
    // 这里可以添加注册成功后的跳转逻辑
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    }
  } finally {
    loading.value = false
  }
}

// 按回车键触发注册（带表单验证）
const onKeyUp = async (e) => {
  if (e.key === 'Enter') {
    try {
      // 先验证表单
      await formRef.value.validate()
      // 验证通过后提交
      await onSubmit()
    } catch (error) {
      // 验证失败会自动显示错误信息
    }
  }
}

// 添加键盘监听
onMounted(() => {
  document.addEventListener('keyup', onKeyUp)
})

// 移除键盘监听
onBeforeUnmount(() => {
  document.removeEventListener('keyup', onKeyUp)
  if (timer) clearInterval(timer)
})

// 暗黑模式切换
const isLight = ref(false)
const isDark = useDark()
const toggleDark = useToggle(isDark)
</script>

<style scoped>
/* The switch - the box around the slider */
.switch {
  font-size: 14px;
  position: relative;
  display: inline-block;
  width: 3.5em;
  height: 2em;
}

/* Hide default HTML checkbox */
.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

/* The slider */
.slider {
  --background: #28096b;
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: var(--background);
  transition: .5s;
  border-radius: 30px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 1.4em;
  width: 1.4em;
  border-radius: 50%;
  left: 10%;
  bottom: 15%;
  box-shadow: inset 8px -4px 0px 0px #fff000;
  background: var(--background);
  transition: .5s;
}

input:checked + .slider {
  background-color: #522ba7;
}

input:checked + .slider:before {
  transform: translateX(100%);
  box-shadow: inset 15px -4px 0px 15px #fff000;
}
</style>